package com.da.javatest.interview.other.print;

/**
 * @author chenlida
 * @date 2020/7/24 14:15
 * @description 两个线程交替打印奇偶
 */
public class PrintOddEven2 {
    private static volatile boolean loopForOdd = true;
    private static volatile boolean loopForEven = true;
    private static volatile int counter = 1;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true) {
                while (loopForOdd) {}

                if (counter > 20) {
                    loopForEven = false;
                    break;
                }

                System.out.println(Thread.currentThread().getName() + counter);
                counter++;

                loopForOdd = true;
                loopForEven = false;
            }
        });
        t1.setName("oddThread-");
        t1.start();

        Thread t2 = new Thread(() -> {
            while (true) {
                while (loopForEven) {}

                if (counter > 20) {
                    loopForOdd = false;
                    break;
                }

                System.out.println(Thread.currentThread().getName() + counter);
                counter++;

                loopForOdd = false;
                loopForEven = true;
            }
        });
        t2.setName("evenThread-");
        t2.start();

        // 先启动奇数线程
        loopForOdd = false;
    }
}
